package com.aiyun.security.demo.security;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Collectors;

import com.aiyun.security.demo.domain.User;
import com.aiyun.security.demo.repository.UserRepository;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component("userDetailsService")
public class UserDetailService implements UserDetailsService {


	private final UserRepository userRepository;

	public UserDetailService(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		Optional<User> userOptional = userRepository.findFirstByLogin(s);
		if (!userOptional.isPresent()) {
			throw  new UsernameNotFoundException("该用户不存在");
		}
		User user = userOptional.get();
		String[] roles = user.getRoles().split(",");
		return new org.springframework.security.core.userdetails.User(
				user.getLogin(),
				user.getPassword(),
				Arrays.stream(roles).map(SimpleGrantedAuthority::new).collect(Collectors.toList())
		);
	}
}
